﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using PhoneApp1;
using PhoneApp1.RouteCodeService;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.Device.Location;
using System.Collections;
using PhoneApp1.ServiceReference1;
using System.Collections.ObjectModel;

namespace TaxiTouchClient
{
    public partial class Taxi_demandes_clients : PhoneApplicationPage
    {

        PhoneApp1.ServiceReference1.Service1Client serv;
        PhoneApp1.ServiceReference1.Taxi taxi;
        int iddemande;
        int i = 0;
        int y = 1;
        int f = 0;
        double distance;
        int numtab;
        int rayon = 5;
        private GeoCoordinate loctaxi;
        private double[,] arrayresults;
        private const string mapKey = @"Ai8yroXkpmcBvxqn1TXtjlQhy3FJcObwJpvgxzOEDfgcvaJlOP2CCdCh585njAjA";
        private List<Demande> listedesdemandes;
        public Taxi_demandes_clients()
        {
            InitializeComponent();
            serv = new PhoneApp1.ServiceReference1.Service1Client();
            loctaxi = new GeoCoordinate();
            if(IsolatedStorageSettings.ApplicationSettings.Contains("Taxi"))
            {
                taxi = (PhoneApp1.ServiceReference1.Taxi) IsolatedStorageSettings.ApplicationSettings["Taxi"];
                loctaxi.Latitude = Convert.ToDouble(taxi.LatitudeTaxi);
                loctaxi.Longitude = Convert.ToDouble(taxi.LongitudeTaxi);
            }
        }

        private void rayon5_Checked(object sender, RoutedEventArgs e)
        {
            rayon = 5;
            f = 0;
        }

        private void rayon10_Checked(object sender, RoutedEventArgs e)
        {
            rayon = 10;
            f = 0;
        }

        private void rayon15_Checked(object sender, RoutedEventArgs e)
        {
            rayon = 15;
            f = 0;
        }

        private void Valider_TaxiDemandesClients_Click(object sender, RoutedEventArgs e)
        {
            serv.SelectAllDemandeClientCompleted += testdemandes;
            serv.SelectAllDemandeClientAsync();
        }

        private void testdemandes(object sender, PhoneApp1.ServiceReference1.SelectAllDemandeClientCompletedEventArgs e)
        {            
            if (f == 0)
            {
                arrayresults = new double[0, 0];
                listedesdemandes2.Clear();
                listedesdemandes2 = new ObservableCollection<Demande>();
                Location loctempe = new Location();
                loctempe.Longitude = loctaxi.Longitude;
                loctempe.Latitude = loctaxi.Latitude;
                listedesdemandes = new List<Demande>();
                listedesdemandes = e.Result.ToList<Demande>();
                Listedemandes(loctempe, rayon, listedesdemandes);
            }
            f += 1;
        }

        private void Retour_TaxiDemandesClients_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }

        private void Listedemandes(PhoneApp1.RouteCodeService.Location locationTaxi, int distance, List<PhoneApp1.ServiceReference1.Demande> demandes)
        {
            arrayresults = new double[listedesdemandes.Count, 2];
            if (demandes.Count > 0)
            {
                PhoneApp1.RouteCodeService.Location loctemp = new PhoneApp1.RouteCodeService.Location();
                loctemp.Latitude = (Double)demandes[0].Latitude_Origine;
                loctemp.Longitude = (Double)demandes[0].Longitude_Origine;
                iddemande = demandes[0].ID_Demande;                
                CalculRoute(locationTaxi, loctemp);
            }

        }

        private void CalculRoute(Location loc1, Location loc2)
        {
            try
            {
                RouteRequest routeRequest = new RouteRequest();

                // Set the credentials using a valid Bing Maps key
                routeRequest.Credentials = new Credentials();
                routeRequest.Credentials.ApplicationId = mapKey;

                // Set the start, stop, and end points
                Waypoint[] waypoints = new Waypoint[2];
                routeRequest.Options = new RouteOptions();
                routeRequest.Options.RoutePathType = RoutePathType.Points;
                routeRequest.UserProfile = new UserProfile();
                routeRequest.UserProfile.DistanceUnit = DistanceUnit.Kilometer;
                waypoints[0] = new Waypoint();
                waypoints[0].Description = "Start";
                waypoints[0].Location = loc1;
                waypoints[1] = new Waypoint();
                waypoints[1].Description = "End";
                waypoints[1].Location = loc2;

                routeRequest.Waypoints = waypoints;

                // Make the calculate route request
                RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService");
                routeService.CalculateRouteCompleted += RouteComplete;

                //var RouteResponse = routeService.CalculateRouteAsync(routeRequest);
                //RouteResult rest = 
                routeService.CalculateRouteAsync(routeRequest);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }

        }

        private void RouteComplete(object sender, CalculateRouteCompletedEventArgs e)
        {
            RouteResult resultat = e.Result.Result;
            distance = resultat.Summary.Distance;
            arrayresults[i, 0] = iddemande;
            arrayresults[i, 1] = distance;
            i++;
            Location loctempe = new Location();
            loctempe.Longitude = loctaxi.Longitude;
            loctempe.Latitude = loctaxi.Latitude;
            if (listedesdemandes.Count - 1 >= y)
            {
                PhoneApp1.RouteCodeService.Location loctemp = new PhoneApp1.RouteCodeService.Location();
                loctemp.Latitude = (Double)listedesdemandes[y].Latitude_Origine;
                loctemp.Longitude = (Double)listedesdemandes[y].Longitude_Origine;
                iddemande = listedesdemandes[y].ID_Demande;
                CalculRoute(loctempe, loctemp);
                y++;
            }
            else
            {
                double[,] testeurbeta = new double[arrayresults.Length / 2, 2];

                RectangleCompare mycompare = new RectangleCompare(arrayresults);
                int[] tagarray = new int[(arrayresults.Length) / 2];
                for (int d = 0; d < arrayresults.Length / 2; d++)
                {
                    tagarray[d] = d;
                }
                Array.Sort(tagarray, mycompare);
                int nombredemandes = 0;
                for (int r = 0; r < arrayresults.Length / 2; r++)
                {
                    if (arrayresults[tagarray[r], 1] <= rayon)
                    {
                        nombredemandes++;
                    }

                }
                double[,] resultfin = new double[nombredemandes, 2];
                for (int r = 0; r < nombredemandes; r++)
                {
                    resultfin[r, 0] = arrayresults[tagarray[r], 0];
                    resultfin[r, 1] = arrayresults[tagarray[r], 1];
                }
                Listdemandes(resultfin);
            }
        }
        private ObservableCollection<Demande> listedesdemandes2 = new ObservableCollection<Demande>();
        private void Listdemandes(double[,] liste)
        {
            int Z = 0;
            while (Z < liste.Length / 2)
            {
                Demande dem = new Demande();
                int id =  int.Parse(liste[Z,0].ToString());
                dem = listedesdemandes.Single(dast => dast.ID_Demande == id);
                dem.Distance = liste[Z, 1];
                //ElementListeDemandeClient t = new ElementListeDemandeClient(dem.Nombre_Personne, dem.Adresse_Origine, liste[Z,1]);
                listedesdemandes2.Add(dem);
                Z++;
            }
            i = 0;
            y = 1;
            //liste_demandes.DataContext = null;
            liste_demandes.DataContext = listedesdemandes2;
            liste_demandes.UpdateLayout();
        }

        private void liste_demandes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox maListe = sender as ListBox;
            PhoneApp1.ServiceReference1.Demande demandeSelected = liste_demandes.SelectedItem as PhoneApp1.ServiceReference1.Demande;
            PhoneApplicationService.Current.State["demandeSelected"] = demandeSelected;
            NavigationService.Navigate(new Uri("/Pages/Taxi_details_demande.xaml", UriKind.Relative));
        }

       
       
            // Add a map layer in which to draw the route.


            // Add the route line to the new layer.
            //myRouteLayer.Children.Add(routeLine);

            //LocationRect rect = new LocationRect(north, west, south, east);
    }
}